define(['jquery','underscore', 'backbone','bootstrap','bootstrap-modal','text!templates/TopNavModuleTemplate.jst',
        'BaseModule'],
		function($, _, Backbone,bt,modal,TopNavModuleTemplate,BaseModule) {
	var topNavContext={};
	_.extend(topNavContext, Backbone.Events);
	var TopNavModuleUrl={
			LogoutUrl:BaseModule.WebRoot+"user/LogoutAction",
			LoginUrl:BaseModule.WebRoot+"user/LoginAction",
			RegisterCheckUserEmailUrl:BaseModule.WebRoot+"user/RegisterCheckUserEmail",
			RegisterCheckUserNameUrl:BaseModule.WebRoot+"user/RegisterCheckUserName",
			captchaImageUrl:BaseModule.WebRoot+"captcha/captchaImage",
			RegisterUserUrl:BaseModule.WebRoot+"user/RegisterUserAction",
			CheckLoginUrl:BaseModule.WebRoot+"user/CheckLogin"
	};
var TopNavModule=Backbone.View.extend({
		 tagName:"div",
		 className:"navbar",
		 template:_.template(TopNavModuleTemplate),
		 events:{
	   		  'click #loginBtn':"loginClick",
	   		  'click #registerBtn':"registerClick",
	   		  'click #logoutBtn':"logout",
	   		  'click #myProfile':"openProfile"
	   	  },
		 initialize:function(){
			 this.loginModel=new CheckLoginModel({"userName":""});
			 this.loginModel.fetch();
			 this.loginModel.bind("change",this.render,this);
			 
			 this.loginPanel=new LoginView();
			 this.registPanel=new RegisterView();
			 this.profilePanel=new UserProfileView({model:this.loginModel});
			 
			 Backbone.Events.on("requestFailed",this.globalError,this);
			 topNavContext.on("loginOk",this.userLoginOk,this);
		 },
	 userLoginOk:function(model){
		 this.loginModel=model;
	 },
	 render:function(){
			$(this.el).html(this.template({'tempId':'Navigatior','data':this.loginModel.toJSON()})); 
			return this;
	 },
   	  loginClick:function(){
   		$(this.loginPanel.render().el).modal({
  			 backdrop:true,
    		    keyboard:true,
    		    show:true
    			});
   		this.loginPanel.$('[name=userName]').focus();
   	 },
   	 
	registerClick:function(){
	   		
	   	$(this.registPanel.render().el).modal({
	  			 backdrop:true,
	    		    keyboard:true,
	    		    show:true
	    			});
	   		this.registPanel.$('[name=userAccount]').focus();
    },
	   	
	logout:function(e){
	   		e.preventDefault();
	   		var curView=this;
	   		$.get(TopNavModuleUrl.LogoutUrl,function(res){
	   			if(res=="success"){
	   				curView.loginModel.set({"userName":""});
	   				window.location.href=BaseModule.WebRoot;
	   			}
	   		});
	   	},
	openProfile:function(){
	   	$(this.profilePanel.render().el).modal({
	   			backdrop:false,
    		    keyboard:true,
    		    show:true
	   	});
	},
	globalError:function(errorData){
	   		if(errorData.errorType==1){
	   			this.loginClick();
	   		}
	}
	   	
});
	
	var RegisterModel= BaseModule.BaseModel.extend({
		 urlRoot:TopNavModuleUrl.RegisterUserUrl,
		 validate:function(attrs){
			 
			 if(attrs.userAccount==null || attrs.userAccount.trim()==''){
	        		return {"tagName":"userAccount","errorMsg":"邮箱不能为空"};
	          }
			 if(attrs.userName==null || attrs.userName.trim()==''){
	        		return {"tagName":"userName","errorMsg":"用户名不能为空"};
	          }
			 if(attrs.password==null || attrs.password.trim()==''){
	        		return {"tagName":"password","errorMsg":"密码不能为空"};
	          }
			 if(attrs.password1==null || attrs.password1.trim()==''){
				 return {"tagName":"password1","errorMsg":"密码不能为空"};
	          }
	         if(attrs.password != attrs.password1){
	        		return {"tagName":"password1","errorMsg":"两次密码不一致"};
	          }
			 if(attrs.captcha==null || attrs.captcha.trim()==''){
				 return {"tagName":"captcha","errorMsg":"验证码不能为空"};
			 }
	          
		 }
	 });
	 
	 var CheckLoginModel= BaseModule.BaseModel.extend({
		 idAttribute:"userId",
		 urlRoot: TopNavModuleUrl.CheckLoginUrl
	 });
	 
	var LoginModel= BaseModule.BaseModel.extend({
		 idAttribute:"userId",
		 urlRoot: TopNavModuleUrl.LoginUrl,
		 validate:function(attr){
			 if(attr.userName == null || attr.userName == ""){
				 return "用户名不能为空";
			 }
			 if(attr.password == null || attr.password == ""){
				 return "密码不能为空";
			 }
		 }
	 });
	 
	 var LoginView =Backbone.View.extend({
		 tagName:"div",
		 className:"modal",
		 template:_.template(TopNavModuleTemplate),
		 events:{
			 'click #loginSubBtn':"login",
			 'keydown [name=password]':"enterKey"
		 },
		 initialize:function(){
		 },
		 render:function(){
			 $(this.el).html(this.template({'tempId':'Login','data':null}));
			 return this;
		 },
		 enterKey:function(e){
			if(e.which == 13){
				this.login(e);
			} 
		 },
		 login:function(e){
			 e.preventDefault();
			 var curView=this;
			 this.model=new LoginModel();
			 this.model.save(this.$('form').serializeJSON(),{
				 success:function(model){
					 if(model.get("userId")){
						 $(curView.el).modal("hide");
						 topNavContext.trigger("loginOk",model);
					 }else{
						 curView.$('[name=password]').next().empty().html("用户名或密码错误！"); 
					 }
					 
			 },error:function(msg){
				 curView.$('[name=password]').next().empty().html("用户名或密码不能为空！"); 
			 }
			 });
		 }
			 
	 });
	 
	 
	 var RegisterView =Backbone.View.extend({
		 tagName:"div",
		 className:"modal",
		 template:_.template(TopNavModuleTemplate),
		 events:{
			 'click #registerSubBtn':"register",
		     'blur [name=userAccount]':"checkEmail",
		     'blur [name=userName]':"checkName",
		     'click #newCaptcha':"captcha"
		 },
		 initialize:function(){},
		 render:function(){
			 $(this.el).html(this.template({'tempId':'Register','data':null}));
			 return this;
		 },
		 checkEmail:function(e){
			 var emailInput=e.srcElement;
			 if($(emailInput).val() == ""){
				 $(emailInput).next().empty().html("邮箱不能为空！");
				 return;
			 }
			 $(emailInput).next().empty();
			 $.post(TopNavModuleUrl.RegisterCheckUserEmailUrl,{"userAccount":$(emailInput).val()},function(res){
				 if(res.success){
					 $(emailInput).next().empty().html("邮箱已经存在，请使用其它邮箱！");
				 }
			 });
		 },
		 checkName:function(e){
			 var nameInput=e.srcElement;
			 if($(nameInput).val() == ""){
				 $(nameInput).next().empty().html("昵称不能为空！");
				 return;
			 }
			 $(nameInput).next().empty();
			 $.post(TopNavModuleUrl.RegisterCheckUserNameUrl,{"userName":$(nameInput).val()},function(res){
				 if(res.success){
					 $(nameInput).next().empty().html("昵称已存在，请使用其它昵称！");
				 }
			 });
		 },
		 register:function(){
			 var curView = this;
	            this.model = new RegisterModel();
	            this.model.bind("error",this.showError,this);
	            this.$('[class=\'help-inline error\']').empty();
	            this.model.save(this.$('form').serializeJSON(), {
	                success: function(model) {
	                	if(model.get("userId")){
	                		curView.showSuccess(model);
	                	}else{
	                		if(model.get("errorMesg")){
	                			alert(model.get("errorMesg"));
	                		}else{
	                			alert("注册失败");
	                		}
	                		
	                	}
	                    
	                },error:function(model,msg,options){
	                	curView.showError(model, msg, options);
	                }
	            });
	        },
	        showError:function(model,msg,options){
	        		this.$('[name='+msg.tagName+']').next().empty().html(msg.errorMsg);
	        },
	        showSuccess:function(model){
	        	this.$('[type=reset]').click();
	        	this.$('form').hide();
	        	this.$('[class=modal-body]').append("<div class=\"alert alert-success\"><p>恭喜："+model.get("userName")+"</p><p>注册成功！</p></div>");
	        },
	        captcha:function(e){
	        	e.preventDefault();
	        	this.$('#captchaImg').hide().attr('src', TopNavModuleUrl.captchaImageUrl+'?' + Math.floor(Math.random()*100) ).fadeIn();
	        }
			 
	 });
	 
	 
	 
	 var UserProfileView=Backbone.View.extend({
    	 tagName:"div",
    	 className:"modal",
    	 template:_.template(TopNavModuleTemplate),
    	 events:{
    		'click #saveEmployeeBtn':"updateProfile",
    		'click #updateProfile':"editProfile"
    	 },
    	 initialize:function(){
    		 this.model.bind("change",this.render,this);
    	 },
    	 render:function(){
    		 $(this.el).html(this.template({'tempId':'UserProfile','data':this.model.toJSON()})); 
    		 this.$('input').hide();
    		 this.$('[class=form-actions]').hide();
    		 return this;
    	 },
    	 updateProfile:function(){
    		 var form=this.$('form');
    		 var curView=this;
    		 this.model.save(form.serializeJSON(),{success:function(data){
    			 curView.showInfo("Update successful!");
    			 curView.closeEditPanel();
    		 }});
    	 },
    	 closeEditPanel:function(){
    		 this.$('strong').show();
    		 this.$('input').hide();
    		 this.$('[class=form-actions]').hide();
    	 },
    	 editProfile:function(e){
    		 e.preventDefault();
    		 this.$('strong').hide();
    		 this.$('input').show();
    		 this.$('[class=form-actions]').show();
    	 },
    	 showInfo:function(msg){
    		 if(!this.mesSpan){
    			 this.mesSpan=this.make("span",{"class":"badge badge-success pull-left"});
    		 }
    		 this.$('[class=\'modal-footer\']').prepend(this.mesSpan);
    		 $(this.mesSpan).html(msg).show('fast').hide(3000);
    	 }
    	 
     });
	 
	 return TopNavModule;
});